
package ocbn.remotelab.experimental;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;

/**
 * Experimental purposes only. Do not mark for Phase III.
 * @author c8yanche
 */
public class PPTestServer extends Thread {

    private DataInputStream in;
    private DataOutputStream out;
    private SocketConnection sck;
    private ServerSocketConnection scn;
    private boolean isConnected;
    private boolean ready;
    private String addr;

    public PPTestServer(String addr) {
        super();
        this.addr = addr;
        isConnected = false;
        ready = false;
    }

    public void run() {
        try {
            System.out.println("***testServer thread running***");
            scn = (ServerSocketConnection) Connector.open(addr);
            System.out.println("****LOCAL ADDRESS = " + scn.getLocalAddress());
            System.out.println("****LOCAL HOST = " + System.getProperty("microedition.hostname"));
            ready = true;
            System.out.println("listening at " + addr);
            sck = (SocketConnection) scn.acceptAndOpen();
            in = sck.openDataInputStream();
            out = sck.openDataOutputStream();

            isConnected = true;

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public boolean isConnected() {
        return isConnected;
    }

    public boolean send(String packet) {
        if (out == null) {
            return false;
        }
        try {
            out.writeUTF(packet);
        } catch (IOException ex) {
            return false;
        }
        return true;
    }

    public String recv() {
        if (in == null) {
            return null;
        }
        try {
            return in.readUTF();
        } catch (IOException ex) {
            return null;
        }
    }

    public void terminate() {
        try {
            in.close();
            out.close();
            sck.close();
            scn.close();
        } catch (IOException ex) {
        }
        if (this.isAlive()) {
            this.interrupt();
        }
    }

    public boolean isReady() {
        return this.ready;
    }

    public String getHostAddr() {

        if (ready) {
            try {
                System.out.println("Server at "+scn.getLocalAddress());
                return scn.getLocalAddress();
            } catch (IOException ex) {
                System.out.println("IOException");
                return "";
            }
        } else {
            System.out.println("Not ready yet..");
            return "";
        }
    }
}
